<?php

namespace app\common\model\xilujob;

use app\common\library\Result;
use think\Db;
use think\Exception;
use think\Model;

class ResumeActionLog extends Model
{
    protected $name = 'xilujob_resume_action_log';
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = false;

    /**
     * 记录操作 判断是否有可用次数并扣减
     * @param $companyId
     * @param $userId
     * @param $resumeId
     */
    public static function record($companyId, $userId, $resumeId) {
        $log = static::where([
            'company_id'=>$companyId, 'user_id'=>$userId, 'resume_id'=>$resumeId
        ])->count();
        if($log) {
            return true;
        }
        $enterpriseinfo = EnterpriseInfo::field('id,resume_action_num')->where('company_id', $companyId)->find();
        if(!$enterpriseinfo) {
            throw new Exception(__('no record'));
        }
        if(Resume::where('id',$resumeId)->count()==0) {
            throw new Exception(__('no record'));
        }
        $num =EnterpriseInfo::getAvailableNum($companyId,'resume_view');
        if($num <= 0) {
            throw new Exception("您购买的套餐中查看简历数已用尽，请前往购买");
        }
        Db::startTrans();
        try {
            $log = new static();
            $log->save(['company_id' => $companyId, 'user_id' => $userId, 'resume_id' => $resumeId]);
            //减少查看数
            EnterpriseInfo::where('company_id', $companyId)->update(['resume_action_num'=>Db::raw('resume_action_num-1')]);

            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
        return true;
    }

    public static function hasLog($companyId, $userId, $resumeId) {
        return static::where([
            'company_id'=>$companyId, 'user_id'=>$userId, 'resume_id'=>$resumeId
        ])->count() > 0;
    }

}
